<template>
  <div class="table-container pull-chheight">
    <!-- :before-open="boxhandleOpen" :before-close="boxhandleClose" @row-dblclick="handleRowDBLClick"
                   @row-click="handleRowClick"  -->
    <avue-crud :option="tableOption" v-model="user" :data="tableData" :table-loading="tableLoading"
               :page="listQuery" ref="crud" @row-save="handleSave"
               @row-update="handleUpdate"
               @row-del="handleDel" @refresh-change="handlerefreshChange" @current-change="handleCurrentChange"
               @search-change="handleSearchChange" @selection-change="handleSelectionChange">
      <template slot="menuRight">
        <!--<el-button v-if="permissions.training_student_un_register_add" title="新增" type="primary" icon="el-icon-plus"
                   @click="handleAdd" circle size="small"></el-button>-->
        <el-button v-if="permissions.training_student_un_register_upd" title="修改" type="primary" icon="el-icon-edit"
                   @click="handleRowEdit" circle size="small"></el-button>
        <!--<el-button v-if="permissions.training_student_un_register_del" title="删除" type="danger" icon="el-icon-delete"
                   circle
                   size="small" @click="handleRowDel"></el-button>-->
      </template>
      <template slot-scope="scope" slot="coachId">
        <el-tag>{{ userIdToName(scope.row.coachId) }}</el-tag>
      </template>
      <template slot-scope="scope" slot="coachIdForm">
        <el-cascader :options="users" v-model="defaultUser" @change="getNodeData"></el-cascader>
        <el-input type="hidden" v-model="user.coachId"></el-input>
      </template>
      <template slot-scope="scope" slot="moneyForm">
        <el-input type="text" v-model="user.money" min="0" placeholder="请输入退费金额"></el-input>
      </template>
    </avue-crud>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {fetchList, addObj, putObj, delObj} from '@/api/training/training_student_register'
  import tabOption from '@/const/training/training_student_register'
  import {validatenull} from '@/util/validate'
  import {findByvalue, findParent2} from '@/util/util.js'
  import {getDeptUserTree, getUserDeptPath, getUserById} from '@/api/user'
  import {remote} from '@/api/dict'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  export default {
    name: 'table_student_un_register',
    directives: {
      waves
    },
    data() {
      return {
        tableSearch: {},
        tableOption: tabOption, // 表格设置属性
        tableData: [], // 表格的数据
        tableRow: {},
        tablePage: 1,
        tableLoading: false,
        tabelObj: {},
        user: {},
        users: [],
        defaultUser: [],
        listQuery: {
          total: 0, // 总共多少页
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        grade: {
          box: false,
          check: []
        },
        callRecordTableData: [],
        callRecordLoading: false,
        total: null,
        nickName: null,
        displayDialog: false,
        form1: {
          fid: '',
          fname: '',
          callCount: '',
          tel1: '',
          intentionLevel: '',
          remark: '',
          followUpStatus: '',
          nextFollowUpDate: '',
          nextDate: ''
        },
        inputDisabled: true,
        dicType: '',
        levelList: [],
        nextFollowUpDateList: [],
        levelRules: true,
        rules: {
          remark: [
            {
              required: this.levelRules,
              message: '请填写放弃原因',
              trigger: 'blur'
            },
            {
              // min: 0,
              max: 200,
              message: '字符长度不得大于200',
              trigger: 'blur'
            }
          ]
        },
        disableLevel: ''
      }
    },
    beforeCreate() {
    },
    created() {
      this.initUserDic()
      this.handleList()
    },
    watch: {},
    mounted() {
    },
    computed: {
      ...mapGetters(['permissions', 'menuAll'])
    },
    props: [],
    methods: {
      fillForm1Data(row) {
        this.form1.fid = row.fid
        this.form1.callCount = row.callCount
        this.form1.tel1 = row.tel1
        this.form1.intentionLevel = row.intentionLevel
        this.form1.fname = row.fname
        this.form1.nextFollowUpDate = row.nextFollowUpDate
      },
      // addFlowup(formName) {
      //
      // },
      changeInputDate(evnet) {
        var d = new Date((new Date()).getTime() + (24 * 60 * 60 * 1000 * (evnet.substr(0, evnet.length - 2))))
        this.form1.nextDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
      },
      cancel(formName) {
        this.displayDialog = false
        this.$refs[formName].resetFields()
      },
      create(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            this.form1.followUpStatus = '跟进'
            for (var i = 0; i < this.levelList.length; i++) {
              if (this.levelList[i].label === this.form1.intentionLevel) {
                this.form1.intentionLevel = this.levelList[i].value
              }
            }
            addObj(this.form1).then(() => {
              this.displayDialog = false
              this.handleList()
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      showAddFlowup(row) {
        this.displayDialog = true
        // this.levelRules = false
        // this.form1 = row
        this.fillForm1Data(row)
        this.dicType = 'intention_level'
        this.disableLevel = 'put'
        remote(this.dicType).then(response => {
          for (var i = 0; i < response.data.length; i++) {
            if (row.intentionLevel === response.data[i].value) {
              this.form1.intentionLevel = response.data[i].label
            }
          }
          this.levelList = response.data
        })
        this.dicType = 'next_follow_up_date'
        remote(this.dicType).then(response => {
          for (var i = 0; i < response.data.length; i++) {
            if (row.followUpStatus === response.data[i].value) {
              this.form1.followUpStatus = response.data[i].label
            }
          }
          this.nextFollowUpDateList = response.data
        })
      },
      initUserDic() {
        getDeptUserTree().then(response => {
          this.users = response.data
        })
      },
      getNodeData(data) {
        this.user.coachId = data[data.length - 1]
      },
      userIdToName(userId) {
        console.log(userId)
        return findParent2(this.users, userId)
      },
      /**
       * 获取用户组织路径
       * @param userId 用户ID
       */
      getUserDeptPath(userId) {
        getUserDeptPath(userId).then(response => {
          this.defaultUser = response.data
        })
      },
      /**
       * @title 刷新数据
       *
       **/
      handlerefreshChange(page) {
        this.handleList(this.tableSearch)
        this.$notify({
          message: `刷新数据成功`,
          type: 'success'
        })
      },
      /**
       * @title 权限更新
       *
       **/
      handleGradeUpdate() {
        this.tabelObj.check = [].concat(this.grade.check)
        this.tabelObj = {}
        this.grade.check = []
        this.grade.box = false
      },
      /**
       * @title 权限选择
       *
       **/
      handleGradeCheckChange(data, checked, indeterminate) {
        if (checked) {
          this.grade.check.push(data.id)
        } else {
          this.grade.check.splice(this.grade.check.indexOf(data.id), 1)
        }
      },
      handleRowEdit() {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要编辑的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        this.handleEdit(this.tableRow[0], -1)
      },
      handleEdit(row, index) {
        this.$refs.crud.rowEdit(row, index)
        if (!validatenull(row.followUpUser)) {
          this.getUserDeptPath(row.followUpUser)
        }
      },
      /**
       * @title 打开权限
       */
      handleGrade(row, index) {
        this.$store.dispatch('GetMenuAll').then(data => {
          this.grade.box = true
          this.tabelObj = row
          this.grade.check = this.tabelObj.check
        })
      },
      /**
       * @title 导出excel
       *
       **/
      handleExport() {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['username', 'name']
          const filterVal = ['username', 'name']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel(tHeader, data, this.filename)
        })
      },
      /**
       * @title 页面改变值
       *
       **/
      handleCurrentChange(val) {
        this.tablePage = val
        this.handleList()
      },
      /**
       * @title 搜索按钮回掉
       *
       **/
      handleSearchChange(form) {
        this.tableSearch = form
        /* this.$notify({
          showClose: true,
          message: JSON.stringify(this.tableSearch),
          type: 'success'
        })*/
        this.handleList(this.tableSearch)
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd() {
        this.$refs.crud.rowAdd()
      },
      /**
       * @title 选中第几行
       * @param row 选中那几行数据
       * @detail 调用crud的toggleSelection方法即可
       *
       **/
      toggleSelection(row) {
        this.$refs.crud.toggleSelection(row)
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        var queryParams = {
          'register_mode': this.tableSearch.registerMode,
          'pay_type': this.tableSearch.payType,
          'class_type': this.tableSearch.classType,
          'is_pay': this.tableSearch.isPay,
          'school_area': this.tableSearch.schoolArea,
          'page': this.listQuery.currentPage,
          'limit': this.listQuery.pageSize
        }
        this.tableLoading = true
        var params = Object.assign({}, queryParams)
        fetchList(params).then(response => {
          this.tableData = response.data.records
          this.listQuery = {
            total: response.data.total
          }
          this.tableLoading = false
        })
      },
      /**
       * @title 当前选中的数据
       * @param val 选中的值
       *
       **/
      handleSelectionChange(val) {
        this.tableRow = val
        // this.$notify({
        //   showClose: true,
        //   message: JSON.stringify(val),
        //   type: 'success'
        // })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave(row, done) {
        done()
        addObj(Object.assign({}, row)).then(() => {
          this.dialogFormVisible = false
          this.handleList()
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      /**
       * @title 行双击
       * @param row 为当前的数据
       * @param event 事件
       *
       **/
      handleRowDBLClick(row, event) {
        this.$notify({
          showClose: true,
          message: '双击',
          type: 'success'
        })
      },

      /**
       * @title 行单机
       * @param row 为当前的数据
       * @param event 事件
       * @param column 列
       *
       **/
      handleRowClick(row, event, column) {
        this.$notify({
          showClose: true,
          message: '单机',
          type: 'success'
        })
      },
      handleRowDel() {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要删除的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        this.handleDel(this.tableRow[0], -1)
      },
      /**
       * @title 数据删除
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       *
       **/
      handleDel(row, index) {
        this.$confirm(`是否确认删除序号为${row.name}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(row).then(response => {
            this.dialogFormVisible = false
            this.handleList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done) {
        putObj(row).then(data => {
          this.handleList()
          this.tableData.splice(index, 1, Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          done()
        })
      },
      /**
       * @title 表单关闭前处理
       * @param done
       *
       **/
      boxhandleClose(done) {
        this.defaultUser = []
        this.$notify({
          showClose: true,
          message: '表单关闭前处理事件',
          type: 'success'
        })
        done()
      },
      boxhandleOpen(show) {
        this.$notify({
          showClose: true,
          message: '表单打开前处理事件',
          type: 'success'
        })
        show()
      },
      handleCallSizeChange(val) {
        this.listQuery.pageSize = val
        this.getCallList()
      },
      handleCallCurrentChange(val) {
        this.listQuery.currentPage = val
        this.getCallList()
      },
      handleCalls() {
        this.getCallList(this.tableRow[0])
      }
    }
  }
</script>

<style lang="scss" scoped>
  .table-container {
    padding: 8px 10px;
  }

  .table-header {
    margin-bottom: 10px;
    & > .el-button {
      padding: 12px 25px;
    }
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
